package com.itheima.ai.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.itheima.ai.service.ChatHistoryService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.model.Media;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MimeType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.stream.Collectors;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

@RestController
@RequestMapping("/ai")
public class ChatController {


    @Autowired
    private ChatClient chatClient;

    @Autowired
    private ChatHistoryService chatHistoryService;

    /**
     * 同步调用
     */
    /*@GetMapping("/chat")
    public String chat(String prompt) {
        return chatClient.prompt()
                .user(prompt)
                .call()
                .content();
    }*/

    /**
     * 流式调用
     */
    @PostMapping(value = "/chat", produces = "text/html;charset=UTF-8")
    public Flux<String> chat(@RequestParam(value = "prompt") String prompt,
                             @RequestParam(value = "chatId") String chatId,
                             @RequestParam(value = "files",required = false) List<MultipartFile> files) {
        chatHistoryService.saveHistory("chat",chatId);
        if (CollectionUtils.isEmpty( files)){
            Flux<String> contents = chatClient.prompt()
                    .user(prompt)
                    .advisors(advisorSpec -> advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY,chatId))
                    .stream()
                    .content();
            return contents;
        }else{
            //2.多模态模型处理
            List<Media> medias = files.stream().map(file -> new Media(MimeType.valueOf(file.getContentType()), file.getResource())
            ).toList();
            //1.请求模型
            Flux<String> content = chatClient.prompt()
                    .user(promptUserSpec -> promptUserSpec.text(prompt).media(medias.toArray(Media[]::new)))
                    //添加会话ID，防止会话混乱
                    .advisors(advisorSpec -> advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                    .stream()
                    .content();
            return content;
        }





    }
}
